/**
 * 
 */
package speculoos.valid;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.collections.MapUtils;

/**
 * A validator that checks presence of key/value pairs in input map. This class
 * checks that the input map effectively contains non null values for all
 * mandatory keys in the Map this validator holds.
 * 
 * @author abailly
 */
public class MapMandatoryValidator extends AtomicValidator {

	/*
	 * map of mandatory key.
	 */
	private Map mandatory;

	/**
	 * Construct an empty mandatory validator. This constructor is for
	 * programmatic adding of a map in configuration.
	 */
	public MapMandatoryValidator() {
		this.mandatory = new HashMap();
	}

	/**
	 * Create a validator with given map. The given map is used as is but it is
	 * guaranteed that its content will never be modified by this object.
	 * 
	 * @param map
	 *            a Map<String,String>
	 */
	public MapMandatoryValidator(Map map) {
		this.mandatory = MapUtils.invertMap(map);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see speculoos.core.Mapper#map(java.lang.Object, java.util.Map)
	 */
	public Object map(Object input, Map env) throws InvalidateException {
		for (Iterator i = mandatory.keySet().iterator(); i.hasNext();) {
			Object k = i.next();
			/* value should be defined - not null */
			if (getTypeHelper().get(input, (String) k) == null)
				throw new InvalidateException(getName()
						+ ": no value provided for " + k);
		}
		return input;
	}

	/**
	 * @return Returns the mandatory.
	 */
	public Map getMandatory() {
		return mandatory;
	}

	/**
	 * @param mandatory
	 *            The mandatory to set.
	 */
	public void setMandatory(Map mandatory) {
		this.mandatory = MapUtils.invertMap(mandatory);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see speculoos.core.Mapper#getName()
	 */
	public String getName() {
		return "MandatoryMapValidator";
	}

}
